package org.vidi.amqp.rpc;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import org.vidi.amqp.common.ConnectionUtils;
import org.vidi.amqp.common.Constants;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;

/**
 * @author vidi
 */
public class RpcServer {
    private static final Pattern PATTERN = Pattern.compile("[^0-9]");

    public static void main(String[] args) {
        try (Connection connection = ConnectionUtils.newSingleConnection();
             Channel channel = connection.createChannel()) {
            channel.queueDeclare(Constants.RPC_QUEUE_NAME, false, false, false, null);
            channel.queuePurge(Constants.RPC_QUEUE_NAME);
            channel.basicQos(1);
            Object monitor = new Object();

            DeliverCallback callback = (consumerTag, delivery) -> {
                AMQP.BasicProperties replyProps = new AMQP.BasicProperties()
                        .builder()
                        .correlationId(delivery.getProperties().getCorrelationId())
                        .build();
                String response = "response-";
                try {
                    String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                    int n = Integer.parseInt(PATTERN.matcher(message).replaceAll(""));

                    System.out.println(" [.] fib(" + n + ")");
                    response += fib(n);
                } catch (RuntimeException e) {
                    System.out.println(" [.] " + e.toString());
                } finally {
                    channel.basicPublish("", delivery.getProperties().getReplyTo(), replyProps, response.getBytes());
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                    synchronized (monitor) {
                        monitor.notify();
                    }
                }
            };

            channel.basicConsume(Constants.RPC_QUEUE_NAME, false, callback, consumerTag -> {
            });

            while (true) {
                synchronized (monitor) {
                    try {
                        monitor.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (TimeoutException | IOException e) {
            e.printStackTrace();
        }
    }

    private static int fib(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return 1;
        }
        return fib(n - 1) + fib(n - 2);
    }
}
